package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ClientTest1 {
    private Socket socket;

    public ClientTest1(){
        try {
            System.out.println("正在连接服务器...");
            socket = new Socket("localhost",8088);
            System.out.println("与服务器建立连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        ServerHandler serverHandler = new ServerHandler();
        Thread t = new Thread(serverHandler);
        t.setDaemon(true);
        t.start();

        try {
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);
            while(true){
                Scanner scan = new Scanner(System.in);
                String data = scan.nextLine();
                if("exit".equals(data)){
                    break;
                }
                pw.println(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ClientTest1 client = new ClientTest1();
        client.start();
    }

    private class ServerHandler implements Runnable{
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String line;
                while((line = br.readLine())!=null){
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
